"""sync"""
import logging as log

from clients.gitcode_clients import GitCodeClient
from django.utils.functional import cached_property
from django.utils import timezone
from db.models.contribution import Issue
from db.models.space import Repository
from db.models.organization import User
from scripts.utils import calculate_duration



class IssuesSyncer:
        def __init__(self, repo_name, owner, client=None):
            self.repo_name = repo_name
            self.owner = owner
            self.client = client or GitCodeClient()
            self.now = self.timezone.localtime().strftime()
        
        @cached_property
        def repo(self):
            return Repository.objects.get(name=self.repo_name)

        @cached_property
        def repo_issues(self):
            return self.client.get_repo_issues(self.owner, self.repo_name)

        @cached_property
        def repo_issues_comments(self):
            return self.client.get_issues_comments(self.owner, self.repo_name)

        def sync(self):
            for issue in self.repo_issues:
                user = issue['user']
                user_default = {'username': user['login'], 'gitcode_name': user['name']}
                detail = {
                    'unique_tag': issue['id'],
                    'repo': self.repo,
                    'title': issue['title'],
                    'desc': issue['body'],
                    'author': User.objects.get_or_create(gitcode_id=user['id'], defaults=user_default),
                    'status': Issue.issue_status_map[issue['state']],
                    'priority': issue['priority'],
                    'delay_duration': calculate_duration(issue['created_at'], issue['finishi_at'] or self.now)
                }
        

class GitCodeSyncer:
    """GitCode 数据同步服务"""

    def __init__(self, repo_name, owner, client=None):
        self.repo_name = repo_name
        self.owner = owner
        self.client = client or GitCodeClient()

    def _init_issue(self, detail):
        """映射 API 数据到 Issue 模型"""

    def sync_issues(self):
        """同步指定仓库的 Issue 数据"""
        issues = self.client.get_repo_issues(self.owner, self.repo_name)
        print('****', issues)

    def full_sync(self):
        self.sync_issues()
